import React, { useState } from 'react';
import { useTablePipeline, features } from 'ali-react-table';
import { FileSearchOutlined } from '#/utils/antdIcons.js';
import { TjTable } from '@/pages/ETrade/components';
import _ from 'lodash';
import { SORT, PROVINCES } from '../../helper';

export default ({ queryForm, choseValue, queryUrlForm, stations, tableData, tableHead }: any) => {
  const handleClick = (e: any, value: string, flag: string, date?: string, crumbsName?: string) => {
    choseValue({ name: value, flag, date, crumbsName });
    e.stopPropagation();
  };

  const goPath = (params: any) => {
    const { flag, value } = params;
    let newQueryForm = _.cloneDeep(queryForm);
    let startDate = '';
    let endDate = '';
    let stationIds: any[] = [];
    let groupIds: any[] = [];

    if (flag.split('__')[0] !== '合计' && stations.length) {
      if (!newQueryForm.dimensionEnum) {
        const _stations = stations.filter((x: any) => flag.split('__')[0] === x._stationName); // 根据stations中的数据取出点击的交易单元，然后在取交易单元id
        startDate = value;
        endDate = value;
        stationIds = [_stations[0]?._stationCode];
        groupIds = [_stations[0]?._regionCode];
      } else {
        const _stations = stations.filter((x: any) => value === x._stationName); // 根据stations中的数据取出点击的交易单元，然后在取交易单元id
        stationIds = [_stations[0]?._stationCode];
        groupIds = [_stations[0]?._regionCode];
        startDate = flag.split('__')[0];
        endDate = flag.split('__')[0];
      }
    } else {
      if (!newQueryForm.dimensionEnum) {
        startDate = value;
        endDate = value;
        stationIds = newQueryForm.stationIds;
        groupIds = newQueryForm.groupIds;
      } else {
        const _stations = stations.filter((x: any) => value === x._stationName); // 根据stations中的数据取出点击的交易单元，然后在取交易单元id
        stationIds = [_stations[0]?._stationCode];
        groupIds = [_stations[0]?._regionCode];
        startDate = newQueryForm.startDate;
        endDate = newQueryForm.endDate;
      }
    }
    newQueryForm = { ...newQueryForm, startDate, endDate, stationIds, groupIds };
    window.open(
      `#/saas/Tianji/ProvinceSpotsReplayNew?queryForm=${encodeURIComponent(
        JSON.stringify(newQueryForm),
      )}`,
    );
  };

  const title = (value: any, record: any) => {
    const { flag, date, crumbsName } = record;
    const titleValue = value.split('-').length > 1 ? value.split('-').join('') : value;
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'flex-start',
          color: `${
            flag.split('__')[1] === 'son' && _.isEmpty(queryUrlForm) ? '#18A0FB' : '#D8D8D8'
          }`,
          cursor: `${
            flag.split('__')[1] === 'son' && _.isEmpty(queryUrlForm) ? 'pointer' : 'default'
          }`,
        }}
      >
        {flag.split('__')[1] === 'son' && _.isEmpty(queryUrlForm) ? (
          <div onClick={() => goPath({ value, flag, crumbsName })}>{titleValue}</div>
        ) : (
          <div>{titleValue}</div>
        )}
        {flag.split('__')[1] === 'parent' ||
        flag.split('__')[0] === '合计' ||
        (flag.split('__')[1] === 'son' && !_.isEmpty(queryUrlForm)) ? (
          <div
            style={{ marginLeft: '10px', color: '#18A0FB', cursor: 'pointer' }}
            onClick={(e: any) => {
              handleClick(e, value, flag, date, crumbsName);
            }}
          >
            <FileSearchOutlined />
          </div>
        ) : null}
      </div>
    );
  };
  // 处理表头
  const getColumns = (columsValue: any[]) => {
    const columns: any[] = [];
    // 添加表格第一列标题
    columns.push({
      name: ' ',
      align: 'left',
      code: 'name',
      width: 120,
      lock: true,
      render: (value: any, record: any) => title(value, record),
    });
    const parentNames: any[] = Object.keys(_.groupBy(columsValue, 'parentName'));
    parentNames.map((item: string) => {
      columns.push({
        name: item,
        align: 'center',
        children: [],
        lock: false,
      });
    });
    columns.map((colItem: any, index: number) => {
      const children: any[] = [];
      columsValue.map((item: any) => {
        if (colItem.name == item.parentName) {
          children.push({
            name: item.name,
            align: 'center',
            width: 100,
            code: item.field,
            render: (value: any) => value || '-',
            features: {
              sortable:
                item.name === '全网基数比例'
                  ? false
                  : () => {
                      return null;
                    },
            },
          });
        }
      });
      columns[index].children = children;
    });
    return columns;
  };
  // 处理表格数据
  const getDataSource = (dataSource: any[]) => {
    const newDataSource: any[] = [];
    dataSource.map((item, index) => {
      item.id = index + 1;
      // eslint-disable-next-line no-param-reassign
      item = Object.assign(item, item.data);
      (item?.children || []).map((y: any, yIndex: number) => {
        y.id = `${index + 1}-${yIndex + 1}`;
        // eslint-disable-next-line no-param-reassign
        y = Object.assign(y, y.data);
        (y?.children || []).map((z: any, zIndex: number) => {
          // eslint-disable-next-line no-param-reassign
          z = Object.assign(z, z.data);
          z.id = `${index + 1}-${yIndex + 1}-${zIndex + 1}`;
        });
      });
      newDataSource.push(item);
    });

    return newDataSource;
  };
  // 处理排序数据
  const removeEmptyRowData = (dataSource: any[], name: string) => {
    const sortDataSource: any[] = [];
    const noSortData: any[] = [];

    dataSource.map((item) => {
      if (!item.data || !item.data[name]) {
        noSortData.push(item);
      } else {
        sortDataSource.push(item);
      }
    });
    return {
      noSortData: noSortData,
      sortDataSource: sortDataSource,
    };
  };

  const dataTable = _.cloneDeep(tableData);
  const [sorts, onChangeSorts] = useState([]);
  const [openKeys, onChangeOpenKeys] = useState(['1']);
  const [dataSource, setDataSource] = useState(getDataSource(dataTable));
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: dataSource, columns: getColumns(tableHead) })
    .primaryKey('id')
    .use(
      features.sort({
        mode: 'single',
        sorts,
        onChangeSorts: (params: any) => {
          if (params.length) {
            const _dataSource = _.cloneDeep(dataSource);
            onChangeSorts(params);
            const total = dataSource[0];
            const spliceData = _dataSource.splice(1);
            const sortData = removeEmptyRowData(spliceData, params[0].code).sortDataSource; // 排序数据
            const noSortData = removeEmptyRowData(spliceData, params[0].code).noSortData; // 不参与排序数据

            let newDataSource = [];
            if (params[0].order === SORT.desc) {
              newDataSource = sortData.sort((a: any, b: any) => {
                return b[params[0].code] - a[params[0].code];
              });
            } else {
              newDataSource = sortData.sort((a: any, b: any) => {
                return a[params[0].code] - b[params[0].code];
              });
            }
            setDataSource([total, ...newDataSource, ...noSortData]);
          } else {
            setDataSource(getDataSource(dataTable));
            onChangeSorts([]);
          }
        },
      }),
    )
    .use(features.treeMode({ openKeys, onChangeOpenKeys }));

  pipeline.appendRowPropsGetter((_row, rowIndex): any => {
    const color = rowIndex % 2 === 0 ? '#222629' : 'rgba(53, 54, 56, 1)';
    return {
      style: { '--bgcolor': color, '--hover-bgcolor': color },
    };
  });

  return (
    <TjTable
      //  className="compact"
      style={{
        '--header-bgcolor': '#353638',
        '--header-color': 'white',
        '--border-color': '#444',
        '--header-row-height': '36px',
        '--font-size': '12px',
        '--cell-border-vertical': '1px solid #444',
        '--header-cell-border-vertical': '1px solid #444',
        '--bgcolor': '#222629',
        '--color': 'white',
        '--hover-bgcolor': '#222629',
        '--cell-padding': '4px 5px',
        marginLeft: '24px',
        border: '1px solid #444',
        borderRadius: '5px',
      }}
      useOuterBorder={true}
      stickyScrollHeight={10}
      useVirtual={{ horizontal: true, vertical: true, header: false }}
      {...pipeline.getProps()}
    />
  );
};
